package com.testdemo.common.base;

import android.support.annotation.CallSuper;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.testdemo.R;
import com.testdemo.common.utils.PageLoader;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lzy.okgo.OkGo;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by dell on 2017/11/28.
 */

public abstract class BaseListFragment<T> extends BaseFragment {
    @Bind(R.id.recyclerView)
    public RecyclerView mRecyclerView;
    @Bind(R.id.twinklingRefreshLayout)
    public TwinklingRefreshLayout mTwinklingRefreshLayout;

    public View mEmptyView;

    public BaseQuickAdapter mAdapter;

    public PageLoader<T> mPageLoader;


    /**
     * 提供分割线的方法
     *
     * @return
     */
    public RecyclerView.ItemDecoration getItemDecoration() {
        return null;
    }

    /**
     * 提供布局id
     *
     * @return
     */
    @Override
    public int getLayoutResourceId() {
        return R.layout.fragment_base_list;
    }

    /**
     * 布局初始化，各种工作可以在这里进行
     */
    @CallSuper
    @Override
    public void init() {
        initRecyclerView();
        setPageLoader();
        initTwinklingRefreshLayout();
    }


    /**
     * 当上拉下拉操作被取消
     */
    public void onGetDataCanceled() {
        try {
            mTwinklingRefreshLayout.finishRefreshing();
        } catch (Exception e) {
        }
        try {
            mTwinklingRefreshLayout.finishLoadmore();
        } catch (Exception e) {
        }
        OkGo.getInstance().cancelTag(this);
    }

    /**
     * 当item被点击
     *
     * @param helper
     * @param item
     */
    public abstract void onItemClick(BaseViewHolder helper, T item);

    /**
     * 提供Item布局id
     *
     * @return
     */
    public abstract int getItemLayoutId();

    /**
     * Item布局设置数据
     *
     * @param helper
     * @param item
     */
    public abstract void setItemData(BaseViewHolder helper, T item);

    /**
     * 获取网络接口数据
     *
     * @param pageIndex
     * @param pageSize
     * @param getDataType
     */
    public abstract void getData(int pageIndex, int pageSize, final int getDataType);


    /**
     * 提供空数据布局
     *
     * @return
     */
    public View getEmptyView() {
        return null;
    }

    /**
     * 在ViewPager（第一次显示）懒加载时用的，直接在Activity中的，不会触发此方法，Activity中请在init()中加载数据
     */
    public void onFirstVisibleInViewPager() {
        mTwinklingRefreshLayout.startRefresh();
        //mPageLoader.initData();
    }

//    @Override
//    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//        // TODO: inflate a fragment view
//        View rootView = super.onCreateView(inflater, container, savedInstanceState);
////        ButterKnife.bind(this, rootView);
//        return rootView;
//    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    protected void initRecyclerView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapter = new BaseQuickAdapter<T, BaseViewHolder>(getItemLayoutId(), new ArrayList<T>()) {
            @Override
            protected void convert(final BaseViewHolder helper, final T item) {
                helper.getConvertView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        onItemClick(helper, item);
                    }
                });
                setItemData(helper, item);
            }


        };
        if (getItemDecoration() != null) {
            mRecyclerView.addItemDecoration(getItemDecoration());
        }

//        else {
//            DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mContext, ConstraintLayout.LayoutParams.VERTICAL);
//            dividerItemDecoration.setDrawable(getResources().getDrawable(R.drawable.divider_horizontal_0_5dp_grey_f5f6fa));
//            mRecyclerView.addItemDecoration(dividerItemDecoration);
//        }

        mRecyclerView.setAdapter(mAdapter);

    }

    private void setPageLoader() {
        mPageLoader = new PageLoader<T>(mAdapter, mAdapter.getData(), true) {
            @Override
            public void getData(int pageIndex, int pageSize, final int getDataType) {
                BaseListFragment.this.getData(pageIndex, pageSize, getDataType);
            }

            @Override
            public void showLoadingDialog() {
//                showProgressDialog();
            }

            @Override
            public void dismissLoadingDialog() {
                dismissProgressDialog();
                mTwinklingRefreshLayout.finishLoadmore();
                mTwinklingRefreshLayout.finishRefreshing();
            }

            @Override
            public void saveCache(List<T> cacheData) {
            }

            @Override
            public List<T> getCache() {
                return null;
            }
        };

        if (mEmptyView == null) {
            if (getEmptyView() == null) {
                mEmptyView = LayoutInflater.from(mActivity).inflate(R.layout.view_empty, null);
            } else {
                mEmptyView = getEmptyView();
            }
            mPageLoader.setNoDateView(mEmptyView);
        }

        mTwinklingRefreshLayout.setEnableOverScroll(false);
    }

    private void initTwinklingRefreshLayout() {
        mTwinklingRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                mPageLoader.getNextPage();
            }

            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                mPageLoader.update();
            }

            @Override
            public void onRefreshCanceled() {
                onGetDataCanceled();
            }

            @Override
            public void onLoadmoreCanceled() {
                onGetDataCanceled();
            }
        });
    }
}
